Imports System.IO
Imports System.Drawing
Imports System.Drawing.Imaging

' Responsible for managing the picture share cache.
Friend Class PictureShareCacheManager
    Private _cachePath As String = String.Empty

    Public Sub New(ByVal cachePath As String)
        If cachePath Is Nothing Then
            Throw New ArgumentNullException("cachePath")
        End If
        ' Cache path is created when needed.
        If (Not Directory.Exists(cachePath)) Then
            Directory.CreateDirectory(cachePath)
        End If

        Me._cachePath = cachePath
    End Sub

    ' Save a picture stream to a provided file name.
    Public Sub Save(ByVal pictureStream As Stream, ByVal pictureName As String)
        ' Construct image from the provided stream.

        Dim pic As Image = System.Drawing.Bitmap.FromStream(pictureStream)

        ' Construct full picture filename.
        ' Note: assuming JPEG image.
        Dim picFullPath As String = Path.Combine(Me._cachePath, pictureName)
        picFullPath = Path.ChangeExtension(picFullPath, ".jpg")

        If File.Exists(picFullPath) Then
            ' Save will not overwrite any files.
            Return
        End If

        ' Perform save to disk drive.
        pic.Save(picFullPath, ImageFormat.Jpeg)
    End Sub
End Class
